package pri.hillchen.std.netty.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 13:34 2018/3/30 0030.
 */
public class NioTimeHandler implements Runnable{
    private String host;
    private int port;
    private Selector selector;
    private SocketChannel socketChannel;
    private volatile boolean stop = false;

    public NioTimeHandler(String host, int port) throws IOException {
        this.host = host;
        this.port = port;

        selector = Selector.open();
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

    }

    @Override
    public void run() {
        try{
            doConnect();
        }catch (Exception e){
            e.printStackTrace();
            System.exit(1);
        }
        while (!stop){
            try{
                //多路复用选择器等待指定时间来获取请求信息
                System.out.println(Thread.currentThread().getName()+ ":等待就绪请求集:" + selector.select(1000));
                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                Iterator<SelectionKey> it = selectionKeys.iterator();
                SelectionKey key = null;
                while (it.hasNext()){
                    key = it.next();
                    it.remove();
                    try{
                        handleReady(key);
                    }catch (Exception e){
                        if(key != null){
                            key.cancel();
                            if(key.channel() != null){
                                key.channel().close();
                            }
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if(selector != null){
            try {
                selector.close();
                selector = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void handleReady(SelectionKey key) throws IOException {
        if(key.isValid()){
            SocketChannel socketChannel = (SocketChannel) key.channel();
            if(key.isConnectable()){
                if(socketChannel.finishConnect()){
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    doWrite(socketChannel);
                }else {
                    System.exit(1);
                }
            }else if(key.isReadable()){
                ByteBuffer bb =ByteBuffer.allocate(1024);
                int readCount = socketChannel.read(bb);
                if(readCount > 0){
                    bb.flip();
                    byte[] bytes = new byte[bb.remaining()];
                    bb.get(bytes);
                    System.out.println("now is :" + new String(bytes));
                    this.stop = true;
                }else{
                    key.cancel();
                    socketChannel.close();
                }
            }
        }
    }

    private void doConnect() throws IOException {
        if(socketChannel.connect(new InetSocketAddress(host,port))){
            socketChannel.register(selector,SelectionKey.OP_READ);
            doWrite(socketChannel);
        }else {
            socketChannel.register(selector,SelectionKey.OP_CONNECT);
        }
    }
    private void doWrite(SocketChannel socketChannel) throws IOException {
        byte[] req = TimeServerHandler.QUERY_TIME_COMMAND.getBytes();
        ByteBuffer byteBuffer = ByteBuffer.allocate(req.length);
        byteBuffer.put(req);
        byteBuffer.flip();
        socketChannel.write(byteBuffer);
        if( !byteBuffer.hasRemaining()){
            System.out.println("send order to server successed!");
        }
    }

}
